import { Router } from 'express';

import Paths from '@src/common/constants/Paths';
import { prisma } from '@src/common/database';
import { jsonResponse } from '@src/common/util/bigint-serializer';

const router = Router();

// ========== Notices (公告 - 用户端) ==========

// GET /api/content/notices
router.get(Paths.Content.Notices, async (req, res) => {
  try {
    const { page = 1, limit = 20, q } = req.query as any
    const p = Math.max(Number(page) || 1, 1)
    const l = Math.min(Math.max(Number(limit) || 20, 1), 100)

    const where: any = { isPublished: true }
    if (q) where.title = { contains: String(q), mode: 'insensitive' }

    const [items, total] = await Promise.all([
      prisma.notice.findMany({
        where,
        skip: (p - 1) * l,
        take: l,
        orderBy: [{ isPinned: 'desc' }, { createdAt: 'desc' }]
      }),
      prisma.notice.count({ where })
    ])

    return jsonResponse(res, { items, total, page: p, limit: l })
  } catch (err) {
    console.error('공지사항 목록 가져오기 실패:', err)
    return res.status(500).json({ error: '공지사항 목록 가져오기 실패' })
  }
})

// GET /api/content/notices/:id
router.get(Paths.Content.Notices + '/:id', async (req, res) => {
  try {
    const { id } = req.params as any
    const notice = await prisma.notice.findUnique({
      where: { id: BigInt(id) }
    })
    
    if (!notice || !notice.isPublished) {
      return res.status(404).json({ error: '공지사항이 존재하지 않습니다' })
    }
    
    return jsonResponse(res, notice)
  } catch (err) {
    console.error('공지사항 상세 정보 가져오기 실패:', err)
    return res.status(500).json({ error: '공지사항 상세 정보 가져오기 실패' })
  }
})

// ========== FAQs (常见问题 - 用户端) ==========

// GET /api/content/faqs
router.get(Paths.Content.Faqs, async (req, res) => {
  try {
    const { page = 1, limit = 20, q } = req.query as any
    const p = Math.max(Number(page) || 1, 1)
    const l = Math.min(Math.max(Number(limit) || 20, 1), 100)

    const where: any = { isPublished: true }
    if (q) where.title = { contains: String(q), mode: 'insensitive' }

    const [items, total] = await Promise.all([
      prisma.faq.findMany({
        where,
        skip: (p - 1) * l,
        take: l,
        orderBy: [{ isPinned: 'desc' }, { createdAt: 'desc' }]
      }),
      prisma.faq.count({ where })
    ])

    return jsonResponse(res, { items, total, page: p, limit: l })
  } catch (err) {
    console.error('FAQ 목록 가져오기 실패:', err)
    return res.status(500).json({ error: 'FAQ 목록 가져오기 실패' })
  }
})

// GET /api/content/faqs/:id
router.get(Paths.Content.Faqs + '/:id', async (req, res) => {
  try {
    const { id } = req.params as any
    const faq = await prisma.faq.findUnique({
      where: { id: BigInt(id) }
    })
    
    if (!faq || !faq.isPublished) {
      return res.status(404).json({ error: 'FAQ가 존재하지 않습니다' })
    }
    
    return jsonResponse(res, faq)
  } catch (err) {
    console.error('FAQ 상세 정보 가져오기 실패:', err)
    return res.status(500).json({ error: 'FAQ 상세 정보 가져오기 실패' })
  }
})

// ========== Advertisements (广告 - 用户端) ==========

// GET /api/content/advertisements - 获取活跃广告列表（前端轮播使用）
router.get('/advertisements', async (req, res) => {
  try {
    const now = new Date();
    const advertisements = await prisma.advertisement.findMany({
      where: {
        isActive: true,
        OR: [
          { startDate: null, endDate: null },
          { startDate: null, endDate: { gte: now } },
          { startDate: { lte: now }, endDate: null },
          { startDate: { lte: now }, endDate: { gte: now } },
        ],
      },
      orderBy: [{ sortOrder: 'asc' }, { createdAt: 'desc' }],
      select: {
        id: true,
        title: true,
        description: true,
        imageUrl: true,
        linkUrl: true,
        sortOrder: true,
      },
    });

    return jsonResponse(res, { advertisements });
  } catch (err) {
    console.error('活跃广告获取失败:', err);
    return res.status(500).json({ error: '活跃广告获取失败' });
  }
});

// POST /api/content/advertisements/:id/click - 记录广告点击（公开接口）
router.post('/advertisements/:id/click', async (req, res) => {
  try {
    const { id } = req.params;

    await prisma.advertisement.update({
      where: { id: BigInt(id) },
      data: { clickCount: { increment: 1 } },
    });

    return jsonResponse(res, { success: true });
  } catch (err) {
    console.error('广告点击记录失败:', err);
    return res.status(500).json({ error: '广告点击记录失败' });
  }
});

export default router;
